package com.ggh.jinjilive.views.live.pk.http;

import com.blankj.utilcode.util.LogUtils;
import com.ggh.jinjilive.common.MerchantSession;
import com.ggh.jinjilive.utils.GlideEngine;
import com.ggh.jinjilive.views.live.pk.commondef.LoginInfo;
import com.ggh.jinjilive.views.live.pk.commondef.LoginResponse;
import com.google.gson.Gson;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.Map;

import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Response;

public class HttpRequests {
    private static final MediaType MEDIA_JSON  = MediaType.parse("application/json; charset=utf-8");
    //单例
    private static HttpRequests instance = null;
    //单例模式，私有构造方法
    private HttpRequests() {
    }
    //获取单例
    public static HttpRequests getInstance() {
        if (null == instance) {
            synchronized (GlideEngine.class) {
                if (null == instance) {
                    instance = new HttpRequests();
                }
            }
        }
        return instance;
    }

    public static long mTimeDiff = 0;        //客户端和服务器时间差，用户连麦和PK请求超时处理



    protected static final String mServerDomain = "https://liveroom.qcloud.com/weapp/live_room"; //RoomService后台域名

    /**
     * 登录
     * @param loginInfo
     */
    public void login(final LoginInfo loginInfo) {
        String url = mServerDomain + "/login".concat(String.format("?sdkAppID=%s&userID=%s&userSig=%s&platform=%s", loginInfo.sdkAppID, loginInfo.userID, loginInfo.userSig, "Android"));
        OkHttpUtils.post().url(url).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Response response, Exception e, int id) {
                LogUtils.d(e.getMessage());
            }

            @Override
            public void onResponse(String response, int id) {
                LogUtils.d("登录成功" + response);
                LoginResponse loginResponse = new Gson().fromJson(response,LoginResponse.class);
                mTimeDiff = System.currentTimeMillis() - loginResponse.timestamp;
                MerchantSession.getInstance().setLiveToken(loginResponse.token);
                MerchantSession.getInstance().setLiveUserID(loginResponse.userID);
            }
        });
    }

    /**
     * 退出登录
     */
    public void logout(){
        String url = mServerDomain.concat(String.format("%s?userID=%s&token=%s", "/logout", MerchantSession.getInstance().getLiveUserID(), MerchantSession.getInstance().getLiveToken()));
        OkHttpUtils.post().url(url).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Response response, Exception e, int id) {
                LogUtils.d(e.getMessage());
            }

            @Override
            public void onResponse(String response, int id) {
            }
        });
    }


    /**
     * 添加推流
     * @param roomID
     * @param userID
     * @param userName
     * @param userAvatar
     * @param pushURL
     */
    public void addPusher(String roomID,String userID,String userName,String userAvatar,String pushURL){
        String url = mServerDomain.concat(String.format("%s?userID=%s&token=%s","/add_anchor", MerchantSession.getInstance().getLiveUserID(), MerchantSession.getInstance().getLiveToken()));
        OkHttpUtils.post().url(url)
                .addParam("roomID", roomID)
                .addParam("userID", userID)
                .addParam("userName", userName)
                .addParam("userAvatar", userAvatar)
                .addParam("pushURL", pushURL)
                .build()
                .execute(new StringCallback() {
            @Override
            public void onError(Call call, Response response, Exception e, int id) {
                LogUtils.d(e.getMessage());
            }

            @Override
            public void onResponse(String response, int id) {
                LogUtils.d("添加推流" + response);
            }
        });
    }



    /**
     * 创建房间（主播调用）
     * <p>
     * 主播开播的正常调用流程是：
     * 1.【主播】调用 startLocalPreview() 打开摄像头预览，此时可以调整美颜参数。
     * 2.【主播】调用 createRoom 创建直播间，房间创建成功与否会通过 {@link} 通知给主播。
     *
     * @param roomID   房间标识，推荐做法是用主播的 userID 作为房间的 roomID，这样省去了后台映射的成本。room ID 可以填空，此时由后台生成。
     * @param roomInfo 房间信息（非必填），用于房间描述的信息，比如房间名称，允许使用 JSON 格式作为房间信息。
     */
    public void createRoom(final String roomID, final String roomInfo){
        String url = mServerDomain + "/create_room";
        OkHttpUtils.post().url(url)
                .addParam("userID",MerchantSession.getInstance().getLiveUserID())
                .addParam("roomID", roomID)
                .addParam("roomInfo", roomInfo)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Response response, Exception e, int id) {
                LogUtils.d(e.getMessage());
            }

            @Override
            public void onResponse(String response, int id) {
                LogUtils.d(response);
                LoginResponse loginResponse = new Gson().fromJson(response,LoginResponse.class);

            }
        });
    }

    /**
     * 设置自定义信息
     * @param roomID
     * @param fieldName
     * @param operation
     * @param value
     */
    public void setCustomField(String roomID, String fieldName,String operation, Object value){
        String url = mServerDomain.concat(String.format("%s?userID=%s&token=%s", "/set_custom_field", MerchantSession.getInstance().getLiveUserID(),MerchantSession.getInstance().getLiveToken()));
        OkHttpUtils.post().url(url)
                .addParam("roomID", roomID)
                .addParam("fieldName", fieldName)
                .addParam("operation", operation)
                .addParam("value", (String) value)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Response response, Exception e, int id) {
                LogUtils.d(e.getMessage());
            }

            @Override
            public void onResponse(String response, int id) {
                LogUtils.d("JSON" + response);
            }
        });
    }

    /**
     * 添加观众
     * @param roomID
     * @param userID
     * @param userInfo
     */
    public void addAudience(String roomID,String userID,String userInfo){
        String url = mServerDomain.concat(String.format("%s?userID=%s&token=%s", "/add_audience", MerchantSession.getInstance().getLiveUserID(),MerchantSession.getInstance().getLiveToken()));
        OkHttpUtils.post().url(url)
                .addParam("roomID", roomID)
                .addParam("userID", userID)
                .addParam("userInfo", userInfo)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Response response, Exception e, int id) {
                LogUtils.d(e.getMessage());
            }

            @Override
            public void onResponse(String response, int id) {
                LogUtils.d("JSON" + response);
            }
        });
    }

    /**
     * 删除观众
     * @param roomID
     * @param userID
     */
    public void deleteAudience(String roomID, String userID){
        String url = mServerDomain.concat(String.format("%s?userID=%s&token=%s", "/delete_audience", MerchantSession.getInstance().getLiveUserID(),MerchantSession.getInstance().getLiveToken()));
        OkHttpUtils.post().url(url)
                .addParam("roomID", roomID)
                .addParam("userID", userID)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Response response, Exception e, int id) {
                LogUtils.d(e.getMessage());
            }

            @Override
            public void onResponse(String response, int id) {
                LogUtils.d("JSON" + response);
            }
        });
    }


    /**
     * 获取自定义信息
     * @param roomID
     */
    public void getCustomInfo(String roomID){
        String url = mServerDomain.concat(String.format("%s?userID=%s&token=%s", "/get_custom_info", MerchantSession.getInstance().getLiveUserID(),MerchantSession.getInstance().getLiveToken()));
        OkHttpUtils.post().url(url).addParam("roomID", roomID).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Response response, Exception e, int id) {
                LogUtils.d(e.getMessage());
            }

            @Override
            public void onResponse(String response, int id) {
                LogUtils.d("JSON" + response);
            }
        });
    }



    /**
     * 获取房间列表
     */
    public void getRoomList(){
        String url = mServerDomain.concat(String.format("%s?userID=%s&token=%s", "/get_room_list", MerchantSession.getInstance().getLiveUserID(),MerchantSession.getInstance().getLiveToken()));
        OkHttpUtils.post().url(url).addParam("cnt", "0").addParam("index", "10000").build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Response response, Exception e, int id) {
                LogUtils.d(e.getMessage());
            }

            @Override
            public void onResponse(String response, int id) {
                LogUtils.d("JSON" + response);
                LoginResponse loginResponse = new Gson().fromJson(response,LoginResponse.class);
            }
        });
    }
}
